package main

import (
	"net"
	"fmt"
	"os"
)

var (
	dataPull = make(chan []byte, 100)
)

func main() {
	addr := net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 5004}
	paddr := net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 5005}
	con, err := net.ListenUDP("udp", &addr)

	if err != nil {
		fmt.Print("Connection error.", err)
		os.Exit(1)
	}

	defer con.Close()
	go sendData(con, &paddr)
	readData(con)
}

func readData(conn *net.UDPConn) {
	data := make([]byte, 1600)
	for {
		n, _, err := conn.ReadFromUDP(data)
		if err != nil {
			fmt.Println("readData ",err)
			continue
		}
		dataPull <- data[:n]
	}
}

func sendData(conn *net.UDPConn, addr *net.UDPAddr) {
	for {
		data := <-dataPull
		n, err := conn.WriteToUDP(data, addr)
		if err != nil {
			fmt.Println("send Data failed!", err)
			continue
		} else {
			fmt.Println("send data length ", n)
		}
	}
}
